package com.xxl.job.executor.service.jobhandler;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xxl.job.core.context.XxlJobHelper;

import cn.hutool.http.HttpUtil;

public class DeviceThread extends Thread {
	private Logger logger = LoggerFactory.getLogger(DeviceThread.class);

	String deviceContrlUrl = "";
	String port = "80";
	List<Map<String, Object>> deviceList = null;
	Map device = null;
	private Object result;
    public Object getResult() { return result;}
    public static Map<Object,Map> ontime=new HashMap<Object,Map>();
    JdbcTemplate commonDao;
    
	public DeviceThread(String serverip, String port, List<Map<String, Object>> list, JdbcTemplate commonDao) {
		this.deviceContrlUrl = serverip;
		this.port = port;
		this.deviceList = list;
		this.commonDao = commonDao;
//		 device=list.get(0);
//		 list.remove(0);
		// TODO Auto-generated constructor stub
	}

	public void run() {
		// 执行

		while (true) {
			if (deviceList.size() > 0) {
				device = deviceList.get(0);
				device.put("begintime", new Date());
				ontime.put(device.get("IP").toString(), device);
				deviceList.remove(0);
			} else
			{
				//便利ontime，如果某条数据的执行时间>2分钟，获取该条数据，并修改开始时间，不跳出，继续执行循环
				Date cur=new Date();
				boolean nodo=true;
				for (Map.Entry<Object, Map> entry : ontime.entrySet()) {
					Date begin=(Date)entry.getValue().get("begintime");
					if(cur.getTime()-begin.getTime()>600000)//10分钟*60秒*1000毫秒
					{
						//10分钟未执行完，重新执行
						device=entry.getValue();
//						device.put("begintime", new Date());//重新计算时间，防止被别人再拿走
						nodo=false;
						break;
					}
				}
				if(nodo)
					break;
				else
					ontime.remove(device.get("IP"));//只给一次重试机会
			}
			String fromTime = "";
			String recodetime = "";// 打卡时间，最后需要保存到zhkqsj 字
			String ip = (String) device.get("IP");
			Object obj = device.get("zhkqsj");
			String url=null;
			logger.info(ip + ":" + port + ":yu:"+deviceList.size()+"====多线程进来了="+deviceContrlUrl  );

			Calendar calendar = Calendar.getInstance();
			String body = null;

			if (obj != null)
				fromTime = obj.toString().replace(".0", "");
			else
				fromTime = new SimpleDateFormat("yyyy-MM-dd 00:00:00").format(calendar.getTime());
			try {
//				deviceContrlUrl="222.124.179.179";
//				port =80;
				
				String currtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());

				url = "http://" + deviceContrlUrl + ":" + port + "/deviceContrl/Treat?ip=" + ip + "&from="
						+ fromTime + "&to=" + currtime;
				
//				RestTemplate restTemplate = new RestTemplate();
//				ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);
//				body = forEntity.getBody();
				
				body = HttpUtil.get(url,500000);//forEntity.getBody();

//				body=getByUrl(url);
				if (body.equals("[]"))
				{
					ontime.remove(ip);
					continue;
				}
				else if (body.startsWith("Served at"))
				{
					ontime.remove(ip);
					continue;
				}
				else
					if(!body.startsWith("[")||! body.endsWith("]"))
					{
						ontime.remove(ip);
						continue;
					}
				List<Kqlsgl> list2 = (new Gson()).fromJson(body, new TypeToken<List<Kqlsgl>>() {
				}.getType());

				int ii = 0;// 从切换班开始调试

				String mSql = "";
				Kqlsgl temp;
				int count = 0;
				logger.info(ip+"-size:"+list2.size());
				for (; ii < list2.size(); ii++) {
					temp = list2.get(ii);

					if (list2.get(ii).getGh() == null)
						continue;

					recodetime = temp.getSj();
					if (count == 10) {
						mSql = "insert into sbxxsj (id_,sbip,gh,kqsj,seq,dqsj) values " + mSql;
						commonDao.execute(mSql);
						mSql = "";
						count = 0;
					} else
						count++;
					/*
					 * 插入数据库 1、拼接sql，每10条数据一条sql语句执行存储
					 */
					if (mSql != "")
						mSql += ",";
					mSql += "('" + currtime + "-" + temp.getGh() + ii + "','" + ip + "','" + temp.getGh() + "','"
							+ temp.getSj() + "'," + ii + ",'" + currtime + "')";
				}
				mSql = "insert into sbxxsj (id_,sbip,gh,kqsj,seq,dqsj) values " + mSql;
				commonDao.execute(mSql);
				// 记录日志
				String endtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((new Date()).getTime());

//				mSql = "insert into kqsblog (id_,sbip,kszxsj,jszxsj,sjjzsj,jls) values ('" + currtime + ip + "','" + ip
//						+ "','" + currtime + "','" + endtime + "','" + recodetime + "','" + list2.size() + "')";
//
//				commonDao.execute(mSql);
				// 保存打卡时间
				mSql = "update kqsbgl set zhkqsj='"+recodetime+"',zhkqjlsj='" + recodetime + "',tbsj='" + endtime + "' where ip='" + ip + "'";
				commonDao.execute(mSql);
				ontime.remove(ip);
			} catch (Exception e) {
				logger.info(e.getMessage());
				continue;
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		//循环处理时间大于1分钟的设备
		
		
		this.result="ok";

	}
	public String getByUrl(String url)
	{	
		boolean isPostMethod = false;//method.equals("POST");
		String method="GET";
		// request
		HttpURLConnection connection = null;
		BufferedReader bufferedReader = null;
		try {
			// connection
			URL realUrl = new URL(url);
			connection = (HttpURLConnection) realUrl.openConnection();

			// connection setting
			connection.setRequestMethod(method);
			connection.setDoOutput(isPostMethod);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setReadTimeout(5 * 1000);
			connection.setConnectTimeout(3 * 1000);
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
			connection.setRequestProperty("Accept-Charset", "application/json;charset=UTF-8");

			// do connection
			connection.connect();

			// data
//			if (isPostMethod && data != null && data.trim().length() > 0) {
//				DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream());
//				dataOutputStream.write(data.getBytes("UTF-8"));
//				dataOutputStream.flush();
//				dataOutputStream.close();
//			}

			// valid StatusCode
			int statusCode = connection.getResponseCode();
			if (statusCode != 200) {
				throw new RuntimeException("Http Request StatusCode(" + statusCode + ") Invalid.");
			}

			// result
			bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			StringBuilder result = new StringBuilder();
			String line;
			while ((line = bufferedReader.readLine()) != null) {
				result.append(line);
			}
			String responseMsg = result.toString();

			XxlJobHelper.log(responseMsg);

			return responseMsg;
		} catch (Exception e) {
			XxlJobHelper.log(e);

//			XxlJobHelper.handleFail();
			return e.getMessage();
		} finally {
			try {
				if (bufferedReader != null) {
					bufferedReader.close();
				}
				if (connection != null) {
					connection.disconnect();
				}
			} catch (Exception e2) {
				XxlJobHelper.log(e2);
			}
		}

//		return "";
	}

}
